package org.anrc.poi;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.location.LocationManager;
import android.net.Uri;
import android.os.IBinder;

public class PoiRadarService extends Service {
	SharedPreferences prefs;
	public static final String USER_PREFERENCES = "USER_PREFERENCES";
	public static final String PREF_ALERT_RADIUS = "PREF_ALERT_RADIUS";
	Cursor poiCursor;
	private int myAlertRadiusValue;
	private static final String POI_PROXIMITY_ALERT = "org.anrc.poi.PoiRadar";

	@Override
	public void onStart(Intent intent, int startId) {
		getPreferences();
		setProximityAlert();

	}

	private void getPreferences() {
		prefs = getSharedPreferences(USER_PREFERENCES, Activity.MODE_PRIVATE);
		int alertRadiusIndex = prefs.getInt(PREF_ALERT_RADIUS, 2);

		if (alertRadiusIndex < 0)
			alertRadiusIndex = 2;
		Resources r = getResources();
		int[] alertRadiusValues = r.getIntArray(R.array.alert_radius_values);

		myAlertRadiusValue = alertRadiusValues[alertRadiusIndex];


	}

	private void setProximityAlert() {
		Thread setProximityAlertThread = new Thread(null,
				backgroundSetProximityAlert, "refresh_poi");
		setProximityAlertThread.start();
	}

	private Runnable backgroundSetProximityAlert = new Runnable() {

		public void run() {
			doSetProximityAlert();
		}
		

		private void doSetProximityAlert() {
			String locService = Context.LOCATION_SERVICE;

			LocationManager locationManager;
			locationManager = (LocationManager) getSystemService(locService);
			
			int radius = myAlertRadiusValue;
			long expiration = -1; // newer
			Uri poiURI = PoiProvider.CONTENT_URI;
			ContentResolver cr = getContentResolver();
			poiCursor = cr.query(poiURI, null, null, null, null);

			PendingIntent[] myProximityPending = new PendingIntent[poiCursor
					.getCount()];
			Intent intent = new Intent(POI_PROXIMITY_ALERT);
			
			int i = 0;
			if (poiCursor.moveToFirst())
				do {

					double lat = poiCursor
							.getDouble(PoiProvider.LONGITUDE_COLUMN);
					double lng = poiCursor
							.getDouble(PoiProvider.LATITUDE_COLUMN);

					myProximityPending[i] = PendingIntent.getBroadcast(
							getBaseContext(), i, intent,
							PendingIntent.FLAG_CANCEL_CURRENT);

					locationManager.addProximityAlert(lat, lng, radius,
							expiration, myProximityPending[i]);
					i++;
				} while (poiCursor.moveToNext());

		}
	};

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

}
